package com.lagou.Stage2.module1.task2;

import javax.swing.plaf.nimbus.State;
import java.sql.*;

public class DBUtils {
    //定义静态常量
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";
    //public static Connection con = null;

    //静态代码块,在类加载的时候自动加载jdbc驱动
    {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取JDBC连接
    public static Connection getConnection(){

        try {
            Connection con = DriverManager.getConnection(URL,USER,PASSWORD);
            return con;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //关闭资源方法
    public static void close(Connection con, Statement stat, Statement ps){
        if (con != null && stat != null) {
            try {
                con.close();
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement stat, Statement ps, ResultSet rs){

        try {
            con.close();
            stat.close();
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
